package com.badibadi.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.badibadi.adapter.PinLunGYAdapter;
import com.badibadi.infos.Discuss;
import com.badibadi.infos.ImageShow;
import com.badibadi.infos.ImgShowModel;
import com.badibadi.infos.Results;
import com.badibadi.infos.User;
import com.badibadi.mytools.CommonUtils;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.Dialog;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.ShareSDKTools;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.R.layout;
import com.badibadi.uniclubber.R.menu;
import com.badibadi.uniclubber.SinaExpressionActivity;
import com.libjph.util.JsonUtil;
import com.libjph.util.StringUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

/**zanPeople
 * 这是图片预览中的评论 PingLunGY
 * 2014-10-21
 * @author Administrator
 * 
 * gengxinPinLun()//从网络更新评论 ShowPinLunList()//显示评论列表
 */
public class PicturePinLunActivity extends BaseActivity {

	protected static final String TAG = "PicturePinLunActivity";
	PinLunGYAdapter gyAdapter;
	ImgShowModel imgShowModel;//从上一个activity中传过来的
	Discuss discuss;//评论的列表
	ListView listview_pinlun;
	ImageView zan;
	EditText send_content;
	TextView admire;
	Button send;
	TextView zanPeople;
	List<User> user;//赞的列表
	LinearLayout all_zan_people;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
					Utils.showMessage(PicturePinLunActivity.this, getResources().getString(R.string.l_net_error));
				} catch (Exception e) {

				}

				break;
			case 2:// 标签更新
				Utils.ExitPrgress(PicturePinLunActivity.this);

				break;
			case 3:
				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
					Utils.showMessage(PicturePinLunActivity.this, getResources().getString(R.string.SystemError));
				} catch (Exception e) {
					// TODO: handle exception
				}
			case 4:// 这是评论的
				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
					// 显示评论列表
					ShowPinLunList();
					// praiseList("photo_img",imgShowModel.getId());
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 5:
				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
					Utils.showMessage(PicturePinLunActivity.this, getResources().getString(R.string.SystemError));
				} catch (Exception e) {

				}
				break;
			case 10:// 评论失败
				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
					Utils.showMessage(PicturePinLunActivity.this, getResources().getString(R.string.l_xb112));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 11:// 更新参加者列表
				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
					// gengxinPraiseList();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 12://已经赞了
				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
		
					zan.setSelected(true);
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 13://
				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
//					gengxinPraiseList();
					zan.setSelected(false);
					zan.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							dianzan();
						}
					});
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 14:// 点赞成功

				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
					Utils.showMessage(PicturePinLunActivity.this,getResources().getString(R.string.l_xb55));
				    dianzhanchenggong();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 15://点赞失败
				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
					Utils.showMessage(PicturePinLunActivity.this,getResources().getString(R.string.l_xb113));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 16://点赞失败
				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
					Utils.showMessage(PicturePinLunActivity.this,getResources().getString(R.string.l_xb113));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 17://获取赞的人的列表
				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
					all_zan_people.setVisibility(View.VISIBLE);
				    initZandeRen();
					
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 18://获取赞的人的列表失败
				Utils.ExitPrgress(PicturePinLunActivity.this);
				try {
//					Utils.showMessage(PicturePinLunActivity.this, "点赞失败");
					all_zan_people.setVisibility(View.GONE);
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			default:
				break;
			}
		}
	};
  //点赞成功
	public void dianzhanchenggong()
	{
		zan.setSelected(true);
		admire.setText(""+(Integer.parseInt(admire.getText().toString())+1));
	}
	//更新赞的人在界面上
	public void initZandeRen() {
		// TODO Auto-generated method stub
		String zanpeople="";
		StringBuffer buff = null;
		int zishu=0;//统计字数,是为了知道什么地方变色
		for(int i=0;i<user.size();i++)
		{
//			zanPeople
			buff=new StringBuffer("");
			buff.append("、"+user.get(i).getNickName());
			if(i>10)
			{
				zishu=buff.length()-1;
				buff.append(getResources().getString(R.string.l_xb114)+user.size()+getResources().getString(R.string.l_xb115));
				break;
			}
			if(i==user.size()-1)
			{
				zishu=buff.length()-1;
				buff.append(getResources().getString(R.string.l_xb86));
			}
		}
		zanpeople=buff.substring(1, buff.length());
		 SpannableStringBuilder style = new SpannableStringBuilder(zanpeople);
		 style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.gray_445879)), 0, zishu, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		 zanPeople.setText(style);
		// String text = String.format(
		// getResources().getString(R.string.fqcjlcyyjtpx), money);
		// SpannableStringBuilder style = new SpannableStringBuilder(text);
		// // 设置指定位置文字的颜色
		// style.setSpan(new ForegroundColorSpan(Color.BLUE), 10,
		// (10 + ("" + money).length()),
		// Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		// fqcj.setText(style);
		
		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_picture_pin_lun);

		imgShowModel = (ImgShowModel) getIntent().getSerializableExtra(
				"imgShowModel");

		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		is_praise();
		/** 评论的popwindows 这里只更新，不显示 */
		// root = this.getLayoutInflater().inflate(
		// R.layout.picture_preview_popwindows, null);
		// 以下是评论的
		ImageView tuxian1 = (ImageView) this.findViewById(R.id.tuxian1);
		zan=(ImageView)this.findViewById(R.id.zan);
		admire = (TextView) this.findViewById(R.id.admire);
		TextView discuss = (TextView) this.findViewById(R.id.discuss);
		TextView share = (TextView) this.findViewById(R.id.share);
		zanPeople = (TextView) this.findViewById(R.id.zanPeople);
		listview_pinlun = (ListView) this.findViewById(R.id.listview_pinlun);
		// TextView delete=(TextView)view.findViewById(R.id.delete);
		send_content = (EditText) this.findViewById(R.id.send_content);
		send = (Button) this.findViewById(R.id.send);
		// TextView lshare=(ImageView)view.findViewById(R.id.ll_share);
		all_zan_people = (LinearLayout) this
				.findViewById(R.id.all_zan_people);
		LinearLayout ll_share = (LinearLayout) this.findViewById(R.id.ll_share);

		ll_share.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(!StringUtil.isNullOrEmpty(imgShowModel.getPath()))
				{
					ShareSDKTools.ShowOneKeyShare(PicturePinLunActivity.this, "分享",
							imgShowModel.getTitle(), "", Constants.BadiDownImgUrl
									+ "/" + imgShowModel.getPath(), null, null, null, null,"photo_img");
				}else
				{
					ShareSDKTools.ShowOneKeyShare(PicturePinLunActivity.this, "分享",
							imgShowModel.getTitle(), "", "", null, null, null, null,"photo_img");
				}
				
			}
		});

		tuxian1.setSelected(true);
		// // 显示评论
		admire.setText("" + imgShowModel.getAdmire());
		// 显示评论
		discuss.setText("" + imgShowModel.getDiscuss());
		// 分享
		share.setText("" + imgShowModel.getshare());
		// ScrollView pop_win = (ScrollView)
		// this.findViewById(R.id.scrollView1);
		// int h = getKH(pop_win, false);
		//    

		gengxinPinLun();
		gengxinZandeRen();
		// ShowDisscuss(imgShowModel.getId(), "photo_img", "" + 99999999,
		// Dialog.getSystemLanguageTypegy(PicturePinLunActivity.this));
	}


    
	 private void gengxinZandeRen() {
		// TODO Auto-generated method stub
		praiseList("photo_img", imgShowModel.getId());
	}
	  /**
     *看赞的人列表---POST
     * @param $type   赞的类型    humor_trends：心情动态    photo：相册   photo_img：图片   record_article：记录（记）  activity：活动   club：俱乐部   
     * @param $contentId  被赞的内容ID
     */
	private void praiseList(final String type,final String contentId) {
		// TODO Auto-generated method stub
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				// list= new ArrayList<Pre_message_total>();
				// String content = Utils.getRequest(Constants.BadiUrl_1+
				// "photo/imgInfo?imgId="+imgId+"&languageType="+languageType);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", type);
				map.put("contentId", contentId);
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "commonality/praiseList");
				//    
				if (content != null) {
					Results results2 = Utils.checkResult_NNN(
							PicturePinLunActivity.this, content);
					if (results2 != null
							&& !results2.getRetmsg().equals("null")) {
//						    
						try {
	
							user=JSONUtils.getListByJsonString(results2.getRetmsg(), User.class);
							// imgShowModel =
							// JSONUtils.getEntityByJsonString(results.getRetmsg(),
							// ImgShowModel.class);
							Message msg = new Message();
							msg.what = 17;
							handler.sendMessage(msg);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
							handler.sendEmptyMessage(18);
						}
					} else {

						handler.sendEmptyMessage(18);
						
					}
				} else {

					handler.sendEmptyMessage(18);
				}

			}
		});
	}
	/*
     * 查看某用户是否赞过某条动态/信息  POST
     * @param $uid  //登录用户ID
     * @param $type  //（必需）动态类型（humor_trends：心情动态，photo：相册，photo_img：图片，record_article：记录（记），club：俱乐部，activity：活动）
     * @param $contentId（必需）动态内容ID
     * return boolean
     */
	public void is_praise()
	{
		String uid=Utils.getUid(PicturePinLunActivity.this);
		String type="photo_img";
	    String contentId=imgShowModel.getId();
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("uid", uid);
		map.put("type", type);
		map.put("contentId", contentId);
		CommonUtils.CommomPostfunction(PicturePinLunActivity.this, Constants.BadiUrl_1+"commonality/is_praise", map, handler, 1, 3, 12, 13);
	}
	
	
	
	
	
	
	// 显示从网络上获取的评论列表评论列表
	private void ShowPinLunList() {
		// TODO Auto-generated method stub
		try {
			if (this.discuss.equals("null")) {
				this.discuss = null;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		ImageView tuxian1 = (ImageView) this.findViewById(R.id.tuxian1);

		ImageView biaoqing=(ImageView)this.findViewById(R.id.biaoqing);
		biaoqing.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(PicturePinLunActivity.this,SinaExpressionActivity.class);
				startActivityForResult(intent, PinLunGYAdapter.BIAO_QING);
			}
		});
		
		
		
		 gyAdapter= new PinLunGYAdapter(
				PicturePinLunActivity.this, this.discuss, imgShowModel.getId(),
				"photo_img", imgShowModel.getUid(), send_content, send);
		gyAdapter
				.setOnRefreshPingLunInterface(new PinLunGYAdapter.PinLunInterface() {
					@Override
					public void DeletePingLunRefresh() {
						// TODO Auto-generated method stub
						gengxinPinLun();
					}
				});
		listview_pinlun.setAdapter(gyAdapter);
	}

	/**
	 * 调用ShowDisscuss从网络上获取评论的数据
	 * 
	 */
	public void gengxinPinLun() {
		/**
		 * 查看某个动态的评论列表---get(必需--配合语言)
		 * 
		 * @param $id
		 *            //(必需)需要查看的动态评论ID
		 * @param $type
		 *            //(必需)动态的类型---photo_img：图片，photo：相册，record_article：记录（记），
		 *            humor_trends:心情动态，club：俱乐部，activity：活动
		 * @param $disNum
		 *            //显示的一级评论数量
		 * @param $l
		 *            ;（必需）//zh-cn 为中文简体，zh-tw 中文繁体 en-us 英文
		 */
		ShowDisscuss(imgShowModel.getId(), "photo_img", "" + 99999999,
				Dialog.getSystemLanguageTypegy(PicturePinLunActivity.this));
	}

	public void dianzan()
	{
		dianzan(PicturePinLunActivity.this, Utils.getUid(PicturePinLunActivity.this), imgShowModel.getId(), imgShowModel.getUid(), "photo_img", 14, 15);
	}
	
	
	/**
	 * 点赞 接口名称 praise_operate 用户的点赞人的id 提交方式$GET
	 * 
	 * @param $uid
	 *            ;//点赞人的id
	 * @param $nid
	 *            ;//被操作内容的Id
	 * @param $nuid
	 *            ;//内容所属人id
	 * @param $type赞的类型
	 *            （record_article，club，humor_trends，photo，activity）
	 *            photo_img
	 * @param hander
	 *            ;
	 * @param Success
	 *            ;成功
	 * @param defalt
	 *            ;失败
	 */
	public void dianzan(final Context context, final String uid,
			final String nid, final String nuid, final String type,
			final int Success, final int defalt) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				String content = Utils.getRequest(Constants.BadiUrl
						+ "praise_operate?uid=" + uid + "&nid=" + nid
						+ "&nuid=" + nuid + "&type=" + type);
//				   
//						+ "type=" + type);
//				   ("数据是：" + content);
				if (content != null) {
//					   ("数据是：" + content);
					Results results = Utils.checkResult_NNN(context, content);
					if (results != null && !results.getRetmsg().equals("null")) {
//						   
						try {

							if (results.isRet()) {

								handler.sendEmptyMessage(Success);
							} else
								handler.sendEmptyMessage(defalt);
						} catch (Exception e) {
							   
						}
					} else {
						handler.sendEmptyMessage(1);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		}).start();

	}

	/**
	 * 查看某个动态的评论列表---get(必需--配合语言)
	 * 
	 * @param $id
	 *            //(必需)需要查看的动态评论ID
	 * @param $type
	 *            //(必需)动态的类型---photo_img：图片，photo：相册，record_article：记录（记），
	 *            humor_trends:心情动态，club：俱乐部，activity：活动
	 * @param $disNum
	 *            //显示的一级评论数量
	 * @param $l
	 *            ;（必需）//zh-cn 为中文简体，zh-tw 中文繁体 en-us 英文
	 */
	private void ShowDisscuss(final String id, final String type,
			final String disNum, String l) {
		Utils.showPrgress(PicturePinLunActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				// String content = Utils.sendRequest(map, Constants.BadiUrl
				// + "friends");
				String l = Dialog
						.getSystemLanguageTypegy(PicturePinLunActivity.this);
				String content = Utils.getRequest(Constants.BadiUrl_1
						+ "commonality/showDisscuss?id=" + id + "&type=" + type
						+ "&disNum=" + disNum + "&l=" + l);
				// + "&page=" + page + "&pageNum=" + 10);
//				   
				if (content != null) {
					Results results = Utils.checkResult_NNN(
							PicturePinLunActivity.this, content);
					if (results != null && !results.getRetmsg().equals("null")) {
//						   
						try {
							discuss = JsonUtil.getEntityByJsonString(
									results.getRetmsg(), Discuss.class);
//							   
							// showDisscuss=discuss.getDiscu().get(0);
							// activityReadingModel=JsonUtil.getEntityByJsonString(results.getRetmsg(),
							// ActivityReadingModel.class);
							handler.sendEmptyMessage(4);
						} catch (Exception e) {
							   
//							   
							// handler.sendEmptyMessage(4);
						}
					} else {

						handler.sendEmptyMessage(3);
					}
				} else {

					handler.sendEmptyMessage(1);
				}
			}
		});
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(requestCode==PinLunGYAdapter.BIAO_QING && resultCode==SinaExpressionActivity.ACTIVITY_BIAOQING)
		{
			if(data!=null)
			{
//				ImageView iv_biaoqing=(ImageView)this.findViewById(R.id.biaoqing);
				EditText send_content=(EditText)this.findViewById(R.id.send_content);
//				String content=send_content.getText().toString();
//				send_content.setText(content+data.getStringExtra("result"));
//				send_content.setSelection(send_content.getText().toString().length());
				
				String content2 = data
						.getStringExtra("result");
				int index=send_content.getSelectionStart();
				Editable edit=send_content.getEditableText();
				edit.insert(index, content2);
			}
			
			
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
}
